/*
 * SpeculationTask.cpp
 *
 *  Created on: Mar 17, 2012
 *      Author: user
 */

#include "SpeculationTask.h"
#include "SpeculationManager.h"
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/select.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <net/if.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <errno.h>
#include <malloc.h>

SpeculationTask::SpeculationTask( string s )
	: m_socket( -1 ), m_signature( s ), m_status( SPS_WAITING )
{
	gettimeofday(&m_timeStamp,NULL);
}

SpeculationTask::~SpeculationTask()
{
	shutdown( m_socket, SHUT_RDWR );
	close( m_socket );
    m_socket = 0;
}

void SpeculationTask::commit()
{
	SpeculationManager* manager = SpeculationManager::Instance();
	manager->commitSpeculation(this);
}

void SpeculationTask::sendCommandToMaster( int command )
{
	write( m_socket, &command, sizeof(int) );
}

void SpeculationTask::recvCommandFromMaster( int *command )
{
	ssize_t ret = 0;
	int recvSize = 0;

	do
	{
		ret = read( m_socket, ((unsigned char*)command) + recvSize, sizeof(int) );
		if( ret != -1 )
		{
			recvSize += ret;
		}
	}
	while( (ret == -1 && errno == EINTR) || recvSize != sizeof(int) );
}

void SpeculationTask::sendToMaster( int size, const void *data )
{
	write( m_socket, data, size );
}

void SpeculationTask::recvFromMaster( int size, void *data )
{
	ssize_t ret = 0;
	int recvSize = 0;

	do
	{
		ret = read( m_socket, ((unsigned char*)data) + recvSize, size - recvSize );
		if( ret != -1 )
		{
			recvSize += ret;
		}
	}
	while( (ret == -1 && errno == EINTR) || recvSize != size);
}
